'use strict';

const _ = require('lodash');
const url = require('url');

function getBody(err1, env) {
  if (!(err1.response && err1.response.debug)) {
    return;
  }
  const err = err1.response.debug;
  const uri = url.parse(err.path);
  const path = uri.pathname;
  const serviceName = path.split('/')[1];
  return {
    msgtype: 'markdown',
    markdown: {
      title: '[接口错误日志]',
      text: `## 接口错误日志\n ### 环境: ${env}\n  ### 错误码: ${
        err.response.code
      }\n  ### RequestId: ${
        err.headers['yc-request-id']
      } \n ### 微服务: ${serviceName}\n  ### 接口路径: ${path}\n### 请求方法: ${
        err.method
      }\n### 请求参数:\n  ${JSON.stringify(err.data) ||
        JSON.stringify(err.query)}\n### 头部信息:\n${JSON.stringify(
        err.headers
      )}\n### 错误内容:\n  ${JSON.stringify(err.response).substring(
        0,
        1000
      )}\n`,
    },
  };
}

module.exports = () => async (ctx, next) => {
  try {
    await next();
  } catch (err) {
    ctx.logger.info(err);
    ctx.status = err.status || 200;

    if (!_.isNumber(err.code) && err.code !== undefined) {
      err.code = -1;
      err.message = '系统繁忙，请稍后重试';
    }

    ctx.body = {
      code: err.code || -1,
      message: err.message || '服务端内部错误',
      debug: err.debug,
      requestId: ctx.trackId,
    };

    ctx.logger.debug('错误处理环节' + ctx);
    if (ctx.app.env === 'dev' || ctx.app.env === 'test') {
      if (err.debug) {
        ctx.app.runInBackground(async () => {
          ctx.logger.debug('发送错误报告');
          await ctx.curl(
            'https://oapi.dingtalk.com/robot/send?access_token=49d8ba2ff4e17cd279487e699ebfbe352c9b7a0c3f01212d384b5c0d653ad638',
            {
              data: getBody(err.debug, ctx.app.env),
              method: 'POST',
              dataType: 'json',
              contentType: 'json',
            }
          );
        });
      }
    }
  }
};
